/**
 * mybank.com Inc.
 * Copyright (c) 2014-2015 All Rights Reserved.
 */
package com.dalgen.mybatis.datasources;

import java.sql.*;
import java.util.List;
import java.util.Map;

import com.dalgen.mybatis.model.db.DataBase;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;

import com.alipay.oceanbase.OceanbaseDataSourceProxy;

/**
 * OB conn
 * 
 * @author hailiang.yang
 * @version $Id: OBConn.java, v 0.1 2015年4月16日 下午6:31:18 hailiang.yang Exp $
 */
public class OBConnection {

    public static Connection getConnection(DataBase dataBase) throws Exception {
        String obUrl = dataBase.getPropertyMapVal("url");
        OceanbaseDataSourceProxy datasource = new OceanbaseDataSourceProxy();
        datasource.setConfigURL(obUrl);
        datasource.init();
        Map<String, String> configurations = datasource.getConfigurations();
        DataBase obDatabase = new DataBase();
        obDatabase.setDriverClass("com.mysql.jdbc.Driver");
        for (Map.Entry entry : configurations.entrySet()) {
            if (StringUtils.equals("username", (String) entry.getKey())) {
                obDatabase.addProperty("userid", (String) entry.getValue());
            } else if (StringUtils.equals("password", (String) entry.getKey())) {
                obDatabase.addProperty("password", (String) entry.getValue());
            } else if (StringUtils.equals("clusterAddress", (String) entry.getKey())) {
                String url = "jdbc:mysql://" + StringUtils.split((String) entry.getValue(), ',')[0];

                String[] obUrlParams = StringUtils.split(StringUtils.split(obUrl, '?')[1], '&');
                for (String obUrlParam : obUrlParams) {
                    if (StringUtils.startsWith(obUrlParam, "dataId")) {
                        url += "/" + StringUtils.split(obUrlParam, '=')[1];
                        break;
                    }
                }
                obDatabase.addProperty("url", url);
                System.out.println(url);

            }
        }
        return JdbcConnection.getConnection(obDatabase);
    }

    public static void main(String[] args) throws Exception {
        DataBase dataBase = new DataBase();
        Map<String, String> p = Maps.newHashMap();
        p.put("url", "http://obconsole.test.alibaba-inc.com/ob-config/config.co?dataId=daily_052");
        dataBase.setPropertyMap(p);
        System.out.println(getConnection(dataBase));
    }

}
